package com.gykfbxxh.imovie.view.user.activity;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.utils.util.AppTools;
import com.app.utils.util.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.base.BaseActivity;
import com.gykfbxxh.imovie.bean.RanNumBean;
import com.gykfbxxh.imovie.bean.info.UserInforBean;
import com.gykfbxxh.imovie.config.ConfigKey;
import com.gykfbxxh.imovie.config.URIContant;
import com.gykfbxxh.imovie.custom.net.ParamMap;
import com.gykfbxxh.imovie.listener.HttpListener;
import com.gykfbxxh.imovie.manager.AppConfigManager;
import com.gykfbxxh.imovie.utils.HttpUtils;

import java.util.Timer;
import java.util.TimerTask;


/**
 * 用户注册页
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_yanzma,tv_button ,tv_gologin;
    private EditText et_phonenum,et_yanzma ,et_password;
    private ImageView iv_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addContentView(R.layout.activity_register);
        setTitle("注册");
        mPageName = "RegisterActivity";
        initView();
    }

    private void initView() {
        et_phonenum = (EditText)findViewById(R.id.et_phonenum);
        et_yanzma = (EditText) findViewById(R.id.et_yanzma);
        et_password = (EditText)findViewById(R.id.et_password);
        tv_yanzma = (TextView)findViewById(R.id.tv_yanzma);
        tv_button = (TextView)findViewById(R.id.tv_button);
        iv_button = (ImageView)findViewById(R.id.iv_button);
        tv_gologin = (TextView)findViewById(R.id.tv_gologin);
        et_phonenum.addTextChangedListener(tw);
        et_password.addTextChangedListener(tw);
        et_yanzma.addTextChangedListener(tw);
        tv_button.setOnClickListener(this);
        tv_yanzma.setOnClickListener(this);
        tv_gologin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_gologin:
                onBackPressed();
                break;
            case R.id.tv_button:
                updatePhone();
                break;
            case R.id.tv_yanzma:
                sendCode();
                break;
        }

    }

    /**
     * 修改密码
     */
    private void updatePhone() {
        if(request_state) return;
        if(et_phonenum==null||et_yanzma==null||et_password==null) {
            return;
        }
        String phoneNum = et_phonenum.getText().toString().trim();
        String code = et_yanzma.getText().toString().trim();
        final String pwd = et_password.getText().toString().trim();
        ParamMap paramMap = new ParamMap();
        paramMap.put("phone",phoneNum);
        paramMap.put("phoneSN", AppTools.getIMEI());
        paramMap.put("code", code);
        paramMap.put("password", pwd);
        paramMap.put("regapp", "4");
        HttpUtils.addPostRequest(URIContant.REGUSER, new TypeToken<UserInforBean>() {
        }.getType(), mPageName, paramMap, new HttpListener<UserInforBean>() {

            @Override
            public void onStart() {
                request_state = true ;
            }

            @Override
            public void onError(VolleyError error) {
                ToastUtils.makeText("注册失败,请稍后再试");
                request_state = false;
            }

            @Override
            public void onSuccess(UserInforBean response) {
                if(response!=null&&"OperateOk".equals(response.getCode())&&response.getResult()!=null) {
                    request_state = true;
                    ToastUtils.makeText("注册成功");
                    SharedPreferences.Editor editor = AppConfigManager.getInstance().getEditor();
                    editor.putString(ConfigKey.USERPWD,pwd);
                    editor.commit();
                    onBackPressed();
                }else {
                    ToastUtils.makeText(response.getErrorMsg());
                    request_state = false;
                }
            }
        });
    }

    private Timer mTimer;//timer
    private static int time;//倒计时
    private static TimerTask mTimerTask;//倒计时任务

    //操作倒计时的操作handler
    private Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            if (time <= 0 && tv_yanzma != null) {
                tv_yanzma.setText("重新发送");
                tv_yanzma.setClickable(true);
                return;
            }
            if (tv_yanzma != null) {
                tv_yanzma.setText("重新发送("+time + ")");
            }
        }
    };

    private void sendCode() {
        if(et_phonenum==null) {
            return;
        }
        String phoneNum = et_phonenum.getText().toString().trim();

        tv_yanzma.setClickable(false);
        if(mTimerTask != null){
            mTimerTask.cancel();
        }
        if (mTimer == null) {
            mTimer = new Timer();
        }
        time = 60;
        tv_yanzma.setText("重新发送("+time + ")");

        mTimerTask = new TimerTask() {

            @Override
            public void run() {
                time--;
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(0);
                }
                if (time <= 0) {
                    cancel();
                }
            }
        };
        mTimer.schedule(mTimerTask, 1000, 1000);

        ParamMap paramMap = new ParamMap();
        paramMap.put("phoneNum",phoneNum);
        paramMap.put("phoneSN", AppTools.getIMEI());
        HttpUtils.addPostRequest(URIContant.GETRANNUM,new TypeToken<RanNumBean>(){}.getType(),mPageName, paramMap, new HttpListener<RanNumBean>() {
            @Override
            public void onError(VolleyError error) {
                ToastUtils.makeText("获取验证码失败");
                if (mTimerTask != null) {
                    mTimerTask.cancel();
                }
                if (tv_yanzma != null) {
                    tv_yanzma.setText("重新发送");
                    tv_yanzma.setClickable(true);
                }
                time = 0;
            }

            @Override
            public void onSuccess(RanNumBean response) {
                if(response!=null&&response.noError()) {
                    //设定倒计时
                    setTimer();
                    ToastUtils.makeText("验证码发送成功");
                }else {
                    if (mTimerTask != null) {
                        mTimerTask.cancel();
                    }
                    if (tv_yanzma != null) {
                        tv_yanzma.setText("重新发送");
                    }
                    time = 0;
                    ToastUtils.makeText(response.getErrorMsg());
                }
            }
        });
    }


    private void setTimer() {
        /**
         * 如果当前有任务进行则 停止任务从新建立一个任务
         * 如果没有任务进行则判断之前是否执行过任务，如果有则不建立任务
         * 如果没有则建立新的任务
         */
        if (time > 0) {
            tv_yanzma.setText("重新发送("+time + ")");
            if (mTimerTask != null) {
                mTimerTask.cancel();
            }
            if (mTimer == null) {
                mTimer = new Timer();
            }
            mTimerTask = new TimerTask() {

                @Override
                public void run() {
                    time--;
                    if (mHandler != null) {
                        mHandler.sendEmptyMessage(0);
                    }
                    if (time <= 0) {
                        cancel();
                    }
                }
            };
            mTimer.schedule(mTimerTask, 1000, 1000);
        } else {
            tv_yanzma.setClickable(true);
            tv_yanzma.setText("重新发送");
        }

    }

    /**
     * edittext的监听
     */
    TextWatcher tw = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(et_phonenum == null || tv_button == null ||iv_button ==null) return;
            if(et_phonenum.getText().toString().trim().length() >= 8) {
                tv_yanzma.setEnabled(true);
                tv_yanzma.setTextColor(Color.rgb(96,96,96));
            }else {
                tv_yanzma.setEnabled(false);
                tv_yanzma.setTextColor(Color.rgb(155,155,155));
            }

            if(et_yanzma.getText().toString().trim().length()>=6
                    && et_password.getText().toString().trim().length()>=6
                    && et_phonenum.getText().toString().trim().length() >= 8) {
                tv_button.setEnabled(true);
                iv_button.setImageResource(R.drawable.confirm_2);
            }else{
                tv_button.setEnabled(false);
                iv_button.setImageResource(R.drawable.confirm);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
}
